import QueryString from 'query-string';
import { callNativeLogin } from '../api';

const parsed = QueryString.parse(location.search);
if (parsed.yyzusercode) {
  sessionStorage.setItem('userCode', parsed.yyzusercode);
}

export function hasLogin(): boolean {
  return !!sessionStorage.getItem('userCode');
}

export function getUserCode(): string {
  const userCode = sessionStorage.getItem('userCode');
  if (!userCode) {
    if (parsed.yyzusercode) {
      sessionStorage.setItem('userCode', parsed.yyzusercode);
      return parsed.yyzusercode;
    } else {
      callNativeLogin().then(resp => {
        sessionStorage.setItem('userCode', resp.data.user_code);
        // window.location.reload();
      }).catch(err => {
        console.error(err);
      });

      return '-1';
    }
  } else {
    return userCode;
  }
  // return localStorage.getItem('userCode') || '14784293';
}
